<?php
$isReloadable = true;
require_once("../../pers/inc.config.php");
require_once(R2_FS_WEB_ROOT.'/app/_inc/inc.session.php');
require_once(R2_FS_WEB_ROOT.'/app/_inc/funct.html.php');
require_once(R2_FS_WEB_ROOT.'/app/util/_inc/funct.confDb.php');

$sTesto = '';
if (reqVar('azione') == 'genera') {
	$msgPag = genera();
}

$sCmdR  = "&nbsp;&nbsp;&nbsp";
$sCmdR .= "<a class='cmd1' href=\"javascript:confGen();\" >"
	."genera</a>";
$sCmdR .=  cmdTorna();
include(R2_FS_WEB_ROOT."/app/util/_inc/inc.aMenuPag.php");
testaHtml('', $msgPag, '30.10.10', $aMenuPag);
?>
<script type="text/javascript">
function confGen() {
	if (confirm("Confermi la generazione dei CSV?")) {
		document.frm1.azione.value='genera';
		document.frm1.submit();
	}
}
</script>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="right" valign='bottom'>
         <? echo $sCmdR;?>
      </td>
   </tr>
</table>
<form name='frm1' action='<?=$_SERVER['PHP_SELF']?>' method='post' enctype="multipart/form-data">
<input type='hidden' name='azione' value="confronta">
<input type='hidden' name='xsn' value="<?=XSN?>">
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
	<tr>
		<td class="tit1" colspan='5' >Genera CSV per fatturazione</td>
	</tr>
	<tr>
		<td class="lab1" width="10%">Mese</td>
		<td class="txt1" width="10%">
			<?php 
			reqDef('mese', date('m',time()-20*24*3600));
			$aMesi = array(1=>'gennaio',2=>'febbraio',3=>'marzo',4=>'aprile',5=>'maggio',6=>'giugno'
				,7=>'luglio',8=>'agosto',9=>'settembre',10=>'ottobre',11=>'novembre',12=>'dicembre');
			echo getHtmlSelect('mese',$aMesi);?>
		</td>
		<td class="lab1" width="10%">Anno</td>
		<td class="txt1" width="20%">
			<?php 
			reqDef('anno', date('Y',time()-20*24*3600));
			$aAnni = array();reqVar('anno');
			for($aaaaX=reqVar('anno')-3; $aaaaX<reqVar('anno')+3; $aaaaX++) {
				$aAnni[$aaaaX] = $aaaaX;
			}
			echo getHtmlSelect('anno',$aAnni);?>
		</td>
		<td class="txt1" width="50%"><b>&nbsp;Data consolidamento&nbsp;:&nbsp;
			<?php echo YMD2DMY(R2_DATA_CONSOLID);?></b>
		</td>
	</tr>
</table>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
<?php 
$aFile = array();
if (defined("R2_FATT_DIR") && $dh = opendir(R2_FATT_DIR)) {
	while($fn = readdir($dh)) {
		if (substr($fn,-4)!='.csv') continue;
		$aFile[substr($fn,0,7)][] = $fn;
	}
}
krsort($aFile);
foreach($aFile as $meseX => $aFilX) {
	sort($aFilX);
	echo "<tr><td class=\"txt1\" align='center'>$meseX</td>\n";
	$nCol = 1;
	foreach($aFilX as $kX => $fnX) {
			$hRefX = "csvDwn.php?fp=".urlencode(R2_FATT_DIR."/$fnX")."&xsn=".XSN;
			echo "<td class=\"txt1\" align='center'><a href=\"$hRefX\" target=\"_blank\" class='txt1'>".
				substr($fnX,8)."</a></td>\n";
			$nCol++;
	}
	while($nCol<9) {
		echo "<td class=\"txt1\">&nbsp;</td>\n";
		$nCol++;
	}
	echo "</tr>\n";
}
?>
</table>
</form>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="right" valign='bottom'>
         <? echo $sCmdR;?>
      </td>
   </tr>
</table>
<?
codaHtml();
exit();

function genera() {
	global $objDB, $objSess, $aUtentiRint, $aStatiRint, $aTipiRint, $aClientiRint, $aRint;
	if (!defined("R2_FATT_DIR")) {
		return "R2_FATT_DIR non definito<br>";
	}
	if (!defined("R2_FATT_TARIFFA_A")) {
		return "R2_FATT_TARIFFA_A non definito<br>";
	}
		if (!defined("R2_FATT_TARIFFA_B")) {
		return "R2_FATT_TARIFFA_B non definito<br>";
	}
	
	$sDataIniz = reqVar('anno').'-'.reqVar('mese').'-01';
	$odx = new rint2Date();
	if ($odx->setYMD($sDataIniz)===false) {
		return 'mese errato<br>';
	} else {
		$dataIniz = $odx->getUnix();
		$sDataFine = $odx->monthLast('ymd');
		$dataFine = $odx->monthLast('unix');
	}
	if (!isset($sCondAgg)) $sCondAgg = '';
	if (!isset($oreGiorn)) $oreGiorn = 7.5;
	$msg = "\r\nInizio elaborazione ".date('Y-m-d',$dataIniz)." - ".date('Y-m-d',$dataFine)."<br>";
	$sSql = "SELECT r.*,SUM(s.stima) AS valutaz FROM attivita a " .
			" INNER JOIN rint r ON r.id_rint = a.id_rint ".
			" LEFT JOIN att_previste s ON s.id_rint = a.id_rint ".
			" WHERE a.data BETWEEN '".date('Y-m-d',$dataIniz)."' AND '".date('Y-m-d',$dataFine)."'" .
			$sCondAgg.
			" GROUP BY a.id_rint ";
	$objDB->query($sSql);
	$aRint = array();
	while($acX = $objDB->fetch()) {
		$aRint[$acX['id_rint']] = $acX;
	}
	$sSql = "SELECT a.*, c.cod_comm, c.descr, c.id_cliente, c.cod_coge FROM attivita a " .
			" LEFT JOIN commessa c ON c.id_comm = a.id_comm ".
			" WHERE a.data BETWEEN '".date('Y-m-d',$dataIniz)."' AND '".date('Y-m-d',$dataFine)."'" .
			$sCondAgg.
			" ORDER BY IF(a.id_rint=0,999999,a.id_rint), c.cod_comm, a.data, a.id_operatore ";
	$objDB->query($sSql);
	$totOre = $totSpese = 0;
	$fileConsunt = R2_FATT_DIR.'/'.date('Y-m',$dataFine)."_adale_consuntivo.csv";
	$fileConsuntOper = R2_FATT_DIR.'/'.date('Y-m',$dataFine)."_adale_consuntivo_oper.csv";
	$fileAnalit = R2_FATT_DIR.'/'.date('Y-m',$dataFine)."_adale_analitica.csv";
	$fileAnalitOper = R2_FATT_DIR.'/'.date('Y-m',$dataFine)."_adale_analitica_oper.csv";
	$fileDettAdale = R2_FATT_DIR.'/'.date('Y-m',$dataFine)."_adale_dettaglio_oper.csv";
	$fileDettQuorum = R2_FATT_DIR.'/'.date('Y-m',$dataFine)."_quorum_dettaglio_oper.csv";
	$fileConsuntQuorum = R2_FATT_DIR.'/'.date('Y-m',$dataFine)."_quorum_consuntivo_oper.csv";
	$fileDettEstat = R2_FATT_DIR.'/'.date('Y-m',$dataFine)."_e-stat_presidio_it.csv";
	if (file_exists($fileConsunt)) unlink($fileConsunt);
	if (file_exists($fileConsuntOper)) unlink($fileConsuntOper);
	if (file_exists($fileAnalit)) unlink($fileAnalit);
	if (file_exists($fileAnalitOper)) unlink($fileAnalitOper);
	if (file_exists($fileDettAdale)) unlink($fileDettAdale);
	if (file_exists($fileDettQuorum)) unlink($fileDettQuorum);
	if (file_exists($fileConsuntQuorum)) unlink($fileConsuntQuorum);
	if (file_exists($fileDettEstat)) unlink($fileDettEstat);
	$aCoGe = array();
	$aCampiOut = array();
	$aCampiOut['data_reg'] = array("\$acZ['data']","D");
	$aCampiOut['operatore'] = array("getOper(\$idOpeX)","D");
	$aCampiOut['cod_comm'] = array("\$acZ['cod_comm']","X");
	$aCampiOut['commessa'] = array("\$acZ['descr']","X");
	$aCampiOut['rint'] = array("(\$idRintX==0)?'':\$idRintX","X");
	$aCampiOut['descr'] = array("getDescrRint(\$idRintX,\$idCliX)","X");
	$aCampiOut['cliente'] = array("getCli(\$idCliX)","X");
	$aCampiOut['riferimento'] = array("getCampoRint(\$idRintX,'rif_esterno')","X");
	$aCampiOut['tipo_attivita'] = array("getTipoAtt(getCampoRint(\$idRintX,'tipo_rint'),\$acZ['tipo_att'])","X");
	$aCampiOut['stato'] = array("getStato(getCampoRint(\$idRintX,'stato'))","X");
	$aCampiOut['valutazione'] = array("getCampoRint(\$idRintX,'valutaz')","X");
	//$aCampiOut['esito'] = array("''","X");
	$aCampiOut['CoGe'] = array("\$acZ['cod_coge']","X");
	$aCampiOut['ore_A'] = array("number_format(\$acZ['ore'],1,',','')","X");
	$aCampiOut['imp_A'] = array("number_format(\$impA,2,',','')","C");
	$aCampiOut['ore_B'] = array("''","X");
	$aCampiOut['imp_B'] = array("''","C");
	$aCampiOut['spese'] = array("number_format(\$acZ['spese'],2,',','')","X");
	
	
	$sRec = $sep = '';
	foreach($aCampiOut as $ncX => $aX) {
		if ($aX[1] == 'C') continue;
		$sRec .= $sep.'"'.$ncX.'"';
		$sep = ';';
	}
	
	$sRec .= "\r\n";
	file_put_contents($fileDettAdale, $sRec,FILE_APPEND);
	file_put_contents($fileDettQuorum, $sRec,FILE_APPEND);
	
	$sRec = $sep = '';
	foreach($aCampiOut as $ncX => $aX) {
		if ($aX[1] == 'D') continue;
		$sRec .= $sep.'"'.$ncX.'"';
		$sep = ';';
	}
	$sRec .= "\r\n";
	file_put_contents($fileConsunt, $sRec,FILE_APPEND);
	file_put_contents($fileConsuntQuorum, $sRec,FILE_APPEND);
	
	$sRec = $sep = '"E-Stat - Presidio IT"'."\r\n";
	$sRec .= $sep = '"data";"operatore";"ore";"luogo";"spese"'."\r\n";
	file_put_contents($fileDettEstat, $sRec,FILE_APPEND);
	
	$totOreA = $totOreB = $totImpA = $totImpB = $totOreNoRint = 0;
	$acX = $objDB->fetch();
	while($acX) {
		$ac1 = $acX;
		$idRintX = $acX['id_rint'];
		$idCommX = $acX['id_comm'];
		$idCliX = getCampoRint($idRintX, 'id_cliente');
		if ($idCliX=='') $idCliX = $acX['id_cliente'];
		$idOpeX = $acX['id_operatore'];
		$oreA = $oreB = $impA = $impB = $speseX = 0;
		while($acX 
		and $idRintX == $acX['id_rint']
		and $idCommX == $acX['id_comm']
		//and $idOpeX == $acX['id_operatore']
		) {
			$acZ = $acX;
			$sRec = $sep = '';
			foreach($aCampiOut as $ncX => $aX) {
				if ($aX[1] == 'C') continue;
				$sEval = "\$vcX = ".$aX[0].";";
				ob_start();
				eval($sEval);
				$sMess = ob_get_flush();
				if ($sMess!='') echo "$sEval : $sMess\r\n";
				$sRec .= $sep.'"'.$vcX.'"';
				$sep = ';';
			}	
			$sRec .= "\r\n";
			file_put_contents($fileDettQuorum, $sRec,FILE_APPEND);
			if ($acZ['id_cliente']!=1) {
				file_put_contents($fileDettAdale, $sRec,FILE_APPEND);
			}
			if ($acZ['cod_comm']=='EST01') {
				$sRec = '"'.$acZ['data'];
				$sRec .= '";"'.getOper($idOpeX);
				$sRec .= '";"'.number_format($acZ['ore'],1,',','');
				$sRec .= '";"'.(($acZ['spese']>0)?"Bologna":"Brescia");
				$sRec .= '";"'.number_format($acZ['spese'],2,',','');
				$sRec .= '"'."\r\n";
				file_put_contents($fileDettEstat, $sRec,FILE_APPEND);
			}
			$oreA += $acX['ore'];
			$impA += round($acX['ore']*R2_FATT_TARIFFA_A/$oreGiorn,2);
			$speseX += $acX['spese'];
			$acX = $objDB->fetch();
		}
		$acZ = $ac1;
		
		$sRec = $sep = '';
		foreach($aCampiOut as $ncX => $aX) {
			if ($aX[1] == 'D') continue;
			$sEval = "\$vcX = ".$aX[0].";";
			ob_start();
			eval($sEval);
			$sMess = ob_get_flush();
			if ($sMess!='') echo "$sEval : $sMess\r\n";
			$sRec .= $sep.'"'.$vcX.'"';
			$sep = ';';
		}
		$sRec .= "\r\n";
		file_put_contents($fileConsuntQuorum, $sRec,FILE_APPEND);
		
		if ($ac1['id_cliente']==1 
		or ($oreA+$oreB)==0) {
			continue;
		}
		$totOreA += $oreA;
		$totOreB += $oreB;
		$totImpA += $impA;
		$totImpB += $impB;
		if ($idRintX == 0) {
			$totOreNoRint += $oreA +$oreB;
		}
		if (!isset($aCoGe[$acZ['cod_coge']])) {
			$aCoGe[$acZ['cod_coge']] = array('A'=>0,'B'=>0,'S'=>0);
		}
		$aCoGe[$acZ['cod_coge']]['A'] += $impA;
		$aCoGe[$acZ['cod_coge']]['B'] += $impB;
		$aCoGe[$acZ['cod_coge']]['S'] += $speseX;
		$totSpese += $speseX;
		$acZ['ore'] = $oreA + $oreB;
		$acZ['spese'] = $speseX;
		$sRec = $sep = '';
		foreach($aCampiOut as $ncX => $aX) {
			if ($aX[1] == 'D') continue;
			$sEval = "\$vcX = ".$aX[0].";";
			ob_start();
			eval($sEval);
			$sMess = ob_get_flush();
			if ($sMess!='') echo "$sEval : $sMess\r\n";
			$sRec .= $sep.'"'.$vcX.'"';
			$sep = ';';
		}
		$sRec .= "\r\n";
		file_put_contents($fileConsunt, $sRec, FILE_APPEND);
	}
	
	
	$sRec = '"";"Percentuale ore no rint";"'.number_format($totOreNoRint*100/($totOreA+$totOreB),1,',','').'%"'
		.';"";"";""'."\r\n";
	file_put_contents($fileConsunt, $sRec, FILE_APPEND);
	$sRec = '"";"";"";"";"Tariffa A - Analista/programmatore esperto";"Tariffa B - Analista/programmatore"'."\r\n";
	file_put_contents($fileConsunt, $sRec, FILE_APPEND);
	
	$sRec = '"";"";"";"Totale ore attivita\' da fatturare ";"'.
		number_format($totOreA,2,',','').'";"'.
		number_format($totOreB,2,',','').'"'."\r\n";
	file_put_contents($fileConsunt, $sRec, FILE_APPEND);
	
	$ggA = round($totOreA/$oreGiorn,2);
	$ggB = round($totOreB/$oreGiorn,2);
	$sRec = '"";"";"";"Totale giorni attivita\' da fatturare";"'.
		number_format($ggA,2,',','').'";"'.
		number_format($ggB,2,',','').'";""'."\r\n";
	file_put_contents($fileConsunt, $sRec, FILE_APPEND);
	
	$sRec = '"";"";"";"Tariffa giornaliera";"'.
		number_format(R2_FATT_TARIFFA_A,2,',','').'";"'.
		number_format(R2_FATT_TARIFFA_B,2,',','').'"'."\r\n";
	file_put_contents($fileConsunt, $sRec,FILE_APPEND);
	
	$sRec = '"";"";"";"Importo";"'.
		number_format($totImpA,2,',','').'";"'.
		number_format($totImpB,2,',','').'"'."\r\n";
	file_put_contents($fileConsunt, $sRec,FILE_APPEND);
	
	$totFatt = $totImpA+$totImpB;
	$sRec = '"";"";"";"Totale fatturato per attivita\' svolte";"'.number_format($totFatt,2,',','').'"'."\r\n";
	file_put_contents($fileConsunt, $sRec,FILE_APPEND);
	
	$sRec = '"";"";"";"Spese";"'.number_format($totSpese,2,',','').'"'."\r\n";
	file_put_contents($fileConsunt, $sRec,FILE_APPEND);
	
	$tot =$totImpA+$totImpB+$totSpese;
	$sRec = '"";"";"";"Totale ";"'.number_format($tot,2,',','').'"'."\r\n";
	file_put_contents($fileConsunt, $sRec,FILE_APPEND);
	
	file_put_contents($fileAnalit, '"codice";"tariffa A";"tariffa B";"importo";"perc.";"spese";"totale"'."\r\n",FILE_APPEND);
	$totImp_A = $totImp_B = $totSpese = 0; 
	foreach($aCoGe as $codX => $aImpX) {
		$totImp_A += $aImpX['A'];
		$totImp_B += $aImpX['B'];
		$totSpese += $aImpX['S'];
	}
	foreach($aCoGe as $codX => $aImpX) {
		$sRec = '"'.$codX.'";"'.
			number_format($aImpX['A'],2,',','').'";"'.
			number_format($aImpX['B'],2,',','').'";"'.
			number_format($aImpX['A']+$aImpX['B'],2,',','').'";"'.
			number_format(($aImpX['A']+$aImpX['B'])*100/($totImp_A+$totImp_B),2,',','').'%";"'.
			number_format($aImpX['S'],2,',','').'";"'.
			number_format($aImpX['A']+$aImpX['B']+$aImpX['S'],2,',','').'"'.
			"\r\n";
		file_put_contents($fileAnalit, $sRec,FILE_APPEND);
	}
	
	$sRec = '"TOTALE";"'.
		number_format($totImp_A,2,',','').'";"'.
		number_format($totImp_B,2,',','').'";"'.
		number_format($totImp_A+$totImp_B,2,',','').'";"'.
		number_format(100,2,',','').'%";"'.
		number_format($totSpese,2,',','').'";"'.
		number_format($totSpese+$totImp_A+$totImp_B,2,',','').'"'.
		"\r\n";
	file_put_contents($fileAnalit, $sRec,FILE_APPEND);
	
	return $msg."Fine elaborazione ".date('Y-m-d',$dataFine)." - Totale ".($totOreA+$totOreB)."\r\n";
}

function getDescrRint($idRint,$idCli=1) {
	global $aRint;
	if ($idRint==0) {
		if ($idCli == 1) { //Quorum
			return "";
		}
		return "Richieste informazioni/Verifiche funzionamento/Modifiche configurazione";
	}
	if (!isset($aRint[$idRint]['descr'])) return "...";
	return $aRint[$idRint]['descr'];
}
function getCampoRint($idRint,$campo) {
	global $aRint;
	if ($idRint==0) {	return ""; }
	if (!isset($aRint[$idRint][$campo])) { return ""; }
	return $aRint[$idRint][$campo];
}
function getCli($id) {
	global $aClientiRint;
	if (!isset($aClientiRint[$id]['nome'])) return $id;
	return $aClientiRint[$id]['nome'];
}
function getTipoAtt($tipoRint,$tipoAtt) {
	global $aTipiRint, $aTipiAttRint;
	if ($tipoRint > 0) {
		if (!isset($aTipiRint[$tipoRint]['des'])) return $tipoRint;
		return $aTipiRint[$tipoRint]['des'];
	}
	if (!isset($aTipiAttRint[$tipoAtt]['des'])) return $tipoAtt;
	return $aTipiAttRint[$tipoAtt]['des'];
}
function getStato($id) {
	global $aStatiRint;
	if (!isset($aStatiRint[$id]['descr'])) return $id;
	return $aStatiRint[$id]['descr'];
}
function getOper($id) {
	global $aUtentiRint;
	if (!isset($aUtentiRint[$id]['nome'])) return $id;
	return $aUtentiRint[$id]['nome'];
}
